package com.qf.service.impl;

import com.qf.classes.Clsses;
import com.qf.dao.ClssesRespository;
import com.qf.service.ClassesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author H
 * @create 2020-11-03 11:09
 * @strive To be whoever you want to be.
 * @Description:
 */
@Service
public class ClassesServiceImpl implements ClassesService {

    @Autowired
    ClssesRespository clssesRespository;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public List<Clsses> findClassByUserId(Integer id) {
        //使用redis进行优化
        List<Clsses> byUserid = null;
        Boolean aBoolean = redisTemplate.hasKey("user_classes_" + id);
        if (aBoolean) {
            System.out.println("从redis中进行查询");
            List o = (List) redisTemplate.opsForValue().get("user_classes_" + id);
            byUserid = o;
        } else {
            System.out.println("从数据库中进行查询");
            byUserid = clssesRespository.findByUserid(id);
            if (byUserid.size() <= 0) {
                redisTemplate.opsForValue().set("user_classes_" + id, null);
                redisTemplate.expire("user_classes_" + id, 60, TimeUnit.SECONDS);
            } else {
                redisTemplate.opsForValue().set("user_classes_" + id, byUserid);
                redisTemplate.expire("user_classes_" + id, 60, TimeUnit.MINUTES);
            }
        }

        return byUserid;
    }
}
